<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Expires" content="0">
    <title>ZhongKui WAF</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <style>
        body{margin:0;font-family:Arial,sans-serif;background-color:#f6f8fa;display:flex;justify-content:center;align-items:flex-start;height:100vh;padding-top:15vh;box-sizing:border-box}
        .verification-container{background:#ffffff;border-radius:12px;box-shadow:0 4px 12px rgba(0,0,0,0.1);width:90%;max-width:400px;padding:30px;text-align:center;box-sizing:border-box}
        .verification-container h1{font-size:24px;color:#333333;margin-bottom:15px}
        .verification-container p{font-size:16px;color:#666666;margin-bottom:20px}
        .progress-bar-container{width:100%;height:10px;background-color:#e9ecef;border-radius:5px;overflow:hidden;margin-bottom:20px}
        .progress-bar{width:0%;height:100%;background-color:#48bb78;transition: width 3s cubic-bezier(0.25, 0.1, 0.25, 1);}
    </style>
</head>

<body>
    <div class="verification-container">
        <h1>安全验证</h1>
        <p id="message">正在进行浏览器安全验证，请稍候...</p>
        <div class="progress-bar-container">
            <div class="progress-bar" id="progressBar"></div>
        </div>
    </div>

    <script>
        var data = {};
        try {
            data = JSON.parse('$request_data');
        } catch (e) {
            data = $request_data;
        }
        var headers = {};
        try {
            headers = JSON.parse('$request_headers');
        } catch (e) {
            headers = $request_headers;
        }
        var result = $formula;

        function verifyPass(data) {
            $.ajax({
                url: window.location.href,
                type: data.method,
                headers: headers,
                data: data.body,
                success: function (response) {
                    $('#message').text('验证通过✓');
                    $('#message').css('color', '#48bb78');
                    setTimeout(function () {
                        document.open();
                        document.write(response);
                        document.close();
                    }, 1000);
                },
                error: function (xhr, status, error) {
                    $('#message').text('请求出错，请刷新页面重试');
                }
            });
        }

        function verify(data) {
            result = result.toString().slice(0, 10);
            $.ajax({
                url: '/captcha/challenge?r=' + Math.random(),
                type: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Captcha-Sign': data['Captcha-Sign'],
                    'Captcha-Time': data['Captcha-Time']
                },
                data: { 'captcha_result': result },
                dataType: "json",
                success: function (response) {
                    if (response.result == "success") {
                        verifyPass(data);
                    } else {
                        $('#message').text('验证失败，请刷新页面重试');
                    }
                },
                error: function (xhr, status, error) {
                    $('#message').text('请求出错，请刷新页面重试');
                }
            });
        }

        function isRealBrowser() {
            const nav = window.navigator;
            const doc = document;
            const win = window;

            try {
                // 1. WebDriver属性检测（兼容旧版Selenium）
                if (nav.webdriver === true || doc.documentElement.getAttribute('webdriver')) {
                    return false;
                }

                if (!String.prototype.includes) {
                    String.prototype.includes = function (search) { return this.indexOf(search) !== -1; };
                }

                // 2. 用户代理关键词检测
                const ua = nav.userAgent.toLowerCase();
                const bannedKeywords = ['headless', 'webdriver', 'puppeteer', 'selenium', 'chromedriver', 'automated', 'phantomjs', 'ghost'];
                if (bannedKeywords.some(function (k) { return ua.includes(k); })) {
                    return false;
                }

                // 3. 移动端检测
                const isMobileUA = /(android|webos|iphone|ipad|ipod|blackberry|windows phone|mobile)/i.test(ua);
                const isMobile = isMobileUA;

                // 4. 插件和MimeType检测
                if (!isMobile) {
                    if (!nav.plugins || !nav.mimeTypes) {
                        return false;
                    }
                    // 类型检查及非空验证
                    if (!nav.plugins || !nav.mimeTypes || Object.prototype.toString.call(nav.plugins) !== '[object PluginArray]' ||
                        Object.prototype.toString.call(nav.mimeTypes) !== '[object MimeTypeArray]') {
                        return false;
                    }
                }

                // 5. 原生函数检测
                const isNative = function (fn) {
                    try {
                        return Function.prototype.toString.call(fn).includes('[native code]');
                    } catch (e) {
                        return false;
                    }
                };
                const nativeChecks = [eval, doc.querySelector, win.setTimeout, win.alert, doc.createElement];
                if (nativeChecks.some(function (f) { return !isNative(f); })) {
                    return false;
                }

                // 6. Headless全局变量检测
                const headlessGlobals = ['callPhantom', '_phantom', '__nightmare', '__webdriver', '__driver_evaluate', '__scenario__'];
                if (headlessGlobals.some(function (p) { return p in win; })) {
                    return false;
                }

                // 7. 权限API特征
                if (typeof navigator.permissions !== 'undefined' && typeof navigator.permissions.query === 'function' && /headless/.test(navigator.permissions.query.toString())) {
                    return false;
                }

                // 8. 屏幕尺寸逻辑（动态阈值区分设备类型）
                const minWidth = isMobile ? 200 : 600;
                const minHeight = isMobile ? 300 : 600;
                const availWidth = window.screen.availWidth || window.screen.width;
                const availHeight = window.screen.availHeight || window.screen.height;

                if (availWidth < minWidth || availHeight < minHeight) {
                    return false;
                }

                // 9. 触摸支持检测（移动端严格模式）
                if (isMobile && (!('ontouchstart' in win) || typeof TouchEvent === 'undefined' || nav.maxTouchPoints < 1)) {
                    return false;
                }

                // 10. 语言属性检测
                if (typeof nav.languages !== 'undefined' && Array.isArray(nav.languages)) {
                    if (!nav.languages.length || nav.languages.some(function (l) {
                        return !l || typeof l !== 'string';
                    })) {
                        return false;
                    }
                }

                // 11. UserAgentData品牌检测（Headless特征）
                if (nav.userAgentData && Array.isArray(nav.userAgentData.brands)) {
                    if (nav.userAgentData.brands.some(function (b) {
                        return b.brand && b.brand.toLowerCase().includes('headless');
                    })) {
                        return false;
                    }
                }

                // 12. WebGL渲染器检测（过滤虚拟渲染）
                const webglCheck = function () {
                    try {
                        const canvas = doc.createElement('canvas');
                        const gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
                        if (!gl) {
                            return false;
                        }
                        const ext = gl.getExtension('WEBGL_debug_renderer_info');
                        if (ext) {
                            const renderer = gl.getParameter(ext.UNMASKED_RENDERER_WEBGL).toLowerCase();
                            if (/(swiftshader|llvmpipe|software)/.test(renderer)) {
                                return false;
                            }
                        }
                        return true;
                    } catch (e) {
                        return false;
                    }
                };
                if (!webglCheck()) {
                    return false;
                }
            } catch (e) {
                return false;
            }

            return true;
        }

        $(function () {
            const progressBar = document.getElementById('progressBar');
            progressBar.style.width = '0%';
            setTimeout(function () {
                progressBar.style.width = '100%';
            }, 10);

            if (isRealBrowser()) {
                setTimeout(function () {
                    verify(data);
                }, 3000);
            } else {
                $('#message').text('验证失败');
            }
        });
    </script>
</body>

</html>